/*
 * dbgout.cpp
 *
 *  Created on: May 8, 2013
 *      Author: zapmunk
 */
#include "headerstop.h"

#ifdef COMPILE_DEBUG

#include "dbgout.h"

using std::cout; using std::endl;
using std::string;
using std::ostream;

namespace _dout {
	dbgbuf* dbgbuf::theDbgbuf = NULL;

	int dbgbuf::sync() {
		if (output()) {
			//str("");
			return 0;
		}

		return -1;
	}
#if OS == OS_LINUX
	bool dbgbuf::output() {
		if (oldStdout) {
			oldCout->operator<<(this);
			return true;
		}
		return false;
	}
	void dbgbuf::init() {}
	void dbgbuf::cleanup() {}
#elif OS == OS_WINDOWS
	bool dbgbuf::output() {
		
	}
	void dbgbuf::init() {

	}
	void dbgbuf::cleanup() {

	}
#else
	//TODO: Support other OSs
	bool dbgbuf::output() {
		//No output for you!
		return false;
	}
	void dbgbuf::init() {}
	void dbgbuf::cleanup() {}
#endif

	bool dbgbuf::commandeerStdout() {
		if (!theDbgbuf) {
			theDbgbuf->init();
			theDbgbuf = new dbgbuf();
			theDbgbuf->oldStdout = cout.rdbuf(theDbgbuf);
			theDbgbuf->oldCout = new ostream(theDbgbuf->oldStdout);
			return true;
		}
		return false;
	}

	bool dbgbuf::releaseStdout() {
		if (theDbgbuf) {
			theDbgbuf->cleanup();
			cout.rdbuf(theDbgbuf->oldStdout);
			delete theDbgbuf->oldCout;
			theDbgbuf->oldCout = NULL;
			theDbgbuf->oldStdout = NULL;
			delete theDbgbuf;
			theDbgbuf = NULL;
			return true;
		}
		return false;
	}
};
#endif
